from openpyxl import load_workbook
import os
from handle_conf import HandleConf
import logging
conf_path = 'conf.ini'
class HandleExcel:
    def __init__(self, file_name, sheet_name):
        self.file_name = file_name
        if not os.path.exists(self.file_name):
            logging.error("文件不存在")
            raise FileNotFoundError("文件不存在")
        self.workbook = load_workbook(self.file_name)
        if sheet_name not in self.workbook.sheetnames:
            logging.error("sheet页不存在")
            raise ValueError("sheet页不存在")
        self.worksheet = self.workbook[sheet_name]
        # 校验表头
        try:
            header_row = self.worksheet[1]
            self.header = [cell.value for cell in header_row]
            print(self.header)
            expected_header_row = load_workbook('../conf/modulecase.xlsx').active[1]
            expected_headers = [cell.value for cell in expected_header_row]
            print(expected_headers)
            if self.header != expected_headers:
                logging.error("表头不匹配!")
                raise ValueError("表头不匹配")
        except (IndexError, AttributeError) as e:
            logging.error(f"表头异常:{e}")
            raise ValueError(f"表头异常:{e}")

    def get_data(self, row_number, column_number):
        """获取指定行的某个数据"""
        if row_number <= 0 or column_number <= 0:
            raise ValueError("行数或列数不能小于0")
        if row_number > self.worksheet.max_row or column_number > self.worksheet.max_column:
            raise ValueError("超出最大行数或最大列数")
        try:
            logging.info(f"获取第{row_number}行第{column_number}列的数据")
            case = self.worksheet[row_number][column_number]
            case_data = case.value
            return case_data
        except Exception as e:
            logging.error(f"获取第{row_number}行第{column_number}列的数据失败:{e}")
            raise ValueError(f"获取第{row_number}行第{column_number}列的数据失败:{e}")

    def write_data(self, row_number, column_number, pass_or_fail):
        """写入测试结果"""
        if row_number <= 0 or column_number <= 0:
            raise ValueError("行数或列数不能小于0")
        if row_number > self.worksheet.max_row or column_number > self.worksheet.max_column:

            raise ValueError("超出最大行数或最大列数")
        try:
            logging.info(f"写入第{row_number}行第{column_number}列的数据")
            if pass_or_fail == "pass":
                self.worksheet[row_number][column_number].value = "PASS"
            else:
                self.worksheet[row_number][column_number].value = "FAIL"
        except Exception as e:
            logging.error(f"写入第{row_number}行第{column_number}列的数据失败:{e}")
            raise ValueError(f"写入第{row_number}行第{column_number}列的数据失败:{e}")


ex = HandleExcel('../testcase/case.xlsx', 'search')
ex.write_data(2, 10, 'pass')


# 报错待修复
# class HandleExcel:
#     # ... 其他类方法不变 ...
#
#     def add_missing_columns(self, target_column, start_row):
#         """
#         添加缺失的列，确保从start_row行开始，至少有target_column列。
#         """
#         current_max_column = self.worksheet.max_column
#         if current_max_column < target_column:
#             for col_num in range(current_max_column + 1, target_column + 1):
#                 self.worksheet.cell(row=start_row, column=col_num).value = ""  # 假设新列填入空字符串
#                 self.worksheet.cell(row=1, column=col_num).value = f"Column {col_num}"  # 假设新列标题为"Column X"
#
#     def write_data(self, row_number, column_number, pass_or_fail):
#         # ... 其他写入数据前的校验逻辑不变 ...
#
#         # 确保从row_number行开始有足够的列
#         self.add_missing_columns(column_number, row_number)
#
#         try:
#             logging.info(f"写入第{row_number}行第{column_number}列的数据")
#             if pass_or_fail == "pass":
#                 self.worksheet[row_number][column_number].value = "PASS"
#             else:
#                 self.worksheet[row_number][column_number].value = "FAIL"
#         except Exception as e:
#             logging.error(f"写入第{row_number}行第{column_number}列的数据失败:{e}")
#             raise ValueError(f"写入第{row_number}行第{column_number}列的数据失败:{e}")
